/**
 * 
 */
package com.milk_shop.dao.imp;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.springframework.stereotype.Component;

import com.milk_shop.dao.FoodDao;
import com.milk_shop.model.Food;

@Component
public class FoodDaoImp extends BaseDao<Food> implements FoodDao {
	
	
	@Override
	public List<Food> getAll() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from food");
		return getList(query);
	}
	
	@Override
	public Food getModelById(int id) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from food where :id=id").setParameter("id", id);
		return getModel(query);
	}

	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@Override
	protected Class<Food> getType() {
		return Food.class;
	}

	@Override
	public List<Food> getFoodByType(int type) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from food where foodType=:type").setParameter("type", type);
		return getList(query);
	}

	@Override
	public List<Food> getRecommendFood() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from food where recommend=" + true);
		return getList(query);
	}

	@Override
	public List<Food> getFoodOrderBySales(boolean isDesc) {
		Session session = sessionFactory.getCurrentSession();
		String order = isDesc ? "desc" : "asc";
		Query query = session.createQuery("from food order by sales "+order);
		return getList(query);
	}
	
	@Override
	public List<Map<String, Object>> getPrecentOfSales() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createSQLQuery
				("SELECT foodtype,SUM(sales)/(SELECT SUM(sales) FROM food)AS precent FROM food GROUP BY foodtype ");
		return query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP).list();
	}
	
	@Override
	public List<Food> getListByPage(int firstResult, int maxResult) {
		Session session=sessionFactory.getCurrentSession();
		List<Food> result = session.createQuery("from food").setFirstResult(firstResult).setMaxResults(maxResult).list();
		return result;
	}

	@Override
	public Food getFoodByName(String name) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from food where :name=name").setParameter("name", name);
		return getModel(query);
	}
	
}
